package com.tcp2.handler;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.SettableFuture;
import com.tcp2.msg.rpc.BaseRes;
import com.tcp2.server.MessageDispatcher;
import com.tcp2.server.ProtoMsgHandler;
import com.tcp2.util.DeferredResultUtil;
import com.yaxon.vndp.dms.DmsContext;
import com.yaxon.vndp.dms.Message;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Author: 程行荣
 * Time: 2014-05-23 10:18
 * Copyright (C) 2014 Xiamen Yaxon Networks CO.,LTD.
 */
public abstract class BaseMsgHandler implements ProtoMsgHandler {
    @Autowired
    protected MessageDispatcher messageDispatcher;


    protected void putFuture(String fno, final DmsContext ctx, final BaseRes errRes) {
        final SettableFuture<Message> sf = SettableFuture.create();
        Futures.addCallback(sf, new FutureCallback<Message>() {
            @Override
            public void onSuccess(Message res) {
                ctx.reply(res);
            }

            @Override
            public void onFailure(Throwable t) {
                errRes.setRc(BaseRes.RC_FAIL);
                ctx.reply(errRes);
            }
        });
        DeferredResultUtil.getInstance().putFuture(fno, sf);
    }
}
